package es.udc.emarketapp.emarket.model.category.dao;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;

import es.udc.emarketapp.emarket.model.category.vo.CategoryVO;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.GeneralOperations;

public class MySQLCategoryDAO extends AbstractSQLCategoryDAO {

   public CategoryVO create(Connection connection, CategoryVO categoryVO)
        throws InternalErrorException{

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {

            // Create "preparedStatement".
            String queryString = "INSERT INTO categoria" +
                "(cat_padre, nom_cat) VALUES (?, ?)";

            preparedStatement = connection.prepareStatement(queryString,
                Statement.RETURN_GENERATED_KEYS);

            // Fill "preparedStatement".

            preparedStatement.setLong(1, categoryVO.getCatPadre());
            preparedStatement.setString(2, categoryVO.getNomCat());

            // Execute query.
            int insertedRows = preparedStatement.executeUpdate();

            if (insertedRows == 0) {
                throw new SQLException("No se pudo insertar la fila a la tabla" +
                    " 'Categoria'");
            }

            if (insertedRows > 1) {
                throw new SQLException("Fila duplicada en la tabla 'Categoria'");
            }
            
            // Get account identifier.
            resultSet = preparedStatement.getGeneratedKeys();

            if (!resultSet.next()) {
                throw new InternalErrorException(new SQLException(
                    "el driver JDBC no ha devuelto el identificador generado"));
            }
            Long idCat = new Long(resultSet.getLong(1));

            // Return the value object.
            return new CategoryVO(idCat, categoryVO.getCatPadre(),
                    categoryVO.getNomCat());
 

        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }

   } //Create
  

}
